package com.chezhujie.www.controller;

import com.chezhujie.www.controller.BaseController;
import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.domain.${simpleClassName};
import com.chezhujie.www.service.${simpleClassName}Service;
import com.chezhujie.www.utils.ConvertObj;
import com.chezhujie.www.utils.Fileupload;
import com.chezhujie.www.utils.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

/**
 *   ${describe}
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/${simpleClassname}")
public class ${simpleClassName}Controller extends BaseController<${simpleClassName}>{
    @Autowired
    private ${simpleClassName}Service ${simpleClassname}Service;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, ${simpleClassName} ${simpleClassname}, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(${simpleClassname},req,model);
    <#list columnList as var>
        <#if 'select'==var.inputType&&('int'==var.inputCode||'str'==var.inputCode)>
        set${var.propertiesUp}(model);
        </#if>
    </#list>
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(${simpleClassname});
            Pagination pagination = ${simpleClassname}Service.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取${describe}列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", ${simpleClassname});
        return "${simpleClassname}/list";
    }
    /**
    * api接口${describe}列表
    * @param pageNo
    * @param pageSize
    * @param ${simpleClassname}
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, ${simpleClassName} ${simpleClassname},
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(${simpleClassname});
            Pagination pagination = ${simpleClassname}Service.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取${describe}列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口${describe}详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = ${simpleClassname}Service.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取${describe}详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "${simpleClassname}/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(${simpleClassName} ${simpleClassname},
        <#list columnList as var>
            <#if 'file'==var.inputType>
            @RequestParam(value = "file${var.propertiesUp}", required = false) MultipartFile multipartFile_${var.propertiesUp},
            </#if>
        </#list>
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(${simpleClassname}.get${keyPropertiesUp}())){
            <#list columnList as var>
                <#if 'file'==var.inputType>
                String ${var.properties} = ${simpleClassname}.get${var.propertiesUp}();
                set${var.propertiesUp}(${simpleClassname},multipartFile_${var.propertiesUp},req);
                </#if>
            </#list>
                ${simpleClassname}Service.update(${simpleClassname});
            <#list columnList as var>
                <#if 'file'==var.inputType>
                Fileupload.deleteFile(req,${var.properties});
                </#if>
            </#list>


            }else{
                ${simpleClassname}.set${keyPropertiesUp}(UUIDUtils.getUUID());
            <#list columnList as var>
                <#if 'file'==var.inputType>
                set${var.propertiesUp}(${simpleClassname},multipartFile_${var.propertiesUp},req);
                </#if>
            </#list>
                ${simpleClassname}Service.insert(${simpleClassname});
            }
            model.addAttribute("success", "保存${describe}成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存${describe}失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }
<#list columnList as var>
    <#if 'file'==var.inputType>
    private void set${var.propertiesUp}(${simpleClassName} ${simpleClassname}, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/${simpleClassname}/"+${simpleClassname}.get${keyPropertiesUp}()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/${simpleClassname}/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String ${var.properties} = "/"+path.replace(basePath, "");
            ${simpleClassname}.set${var.propertiesUp}(${var.properties});
        }
    }
    </#if>
</#list>


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)${keyTypeSimple} ${keyProperties},${simpleClassName} ${simpleClassname}, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(${simpleClassname},req,model);
<#list columnList as var>
    <#if 'select'==var.inputType&&('int'==var.inputCode||'str'==var.inputCode)>
        set${var.propertiesUp}(model);
    </#if>
</#list>
        try {
            ${simpleClassName} entity = ${simpleClassname}Service.queryById(${simpleClassname}.get${keyPropertiesUp}());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询${describe}出错!详情："+e.getMessage());
        }
        return "${simpleClassname}/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(${simpleClassName} ${simpleClassname}, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(${simpleClassname},req,model);
<#list columnList as var>
<#if 'select'==var.inputType&&('int'==var.inputCode||'str'==var.inputCode)>
        set${var.propertiesUp}(model);
</#if>
</#list>
        if(StringUtils.isNotBlank(${simpleClassname}.get${keyPropertiesUp}())){
            ${simpleClassname} = ${simpleClassname}Service.queryById(${simpleClassname}.get${keyPropertiesUp}());
            model.addAttribute("entity", ${simpleClassname});
        }
        return "${simpleClassname}/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)${keyTypeSimple} ${keyProperties},${simpleClassName} ${simpleClassname}, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            ${simpleClassname}Service.deleteById(${simpleClassname}.get${keyPropertiesUp}());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
<#list columnList as var>
    <#if 'select'==var.inputType&&('int'==var.inputCode||'str'==var.inputCode)>
    private void set${var.propertiesUp}(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> list${var.propertiesUp} = ${simpleClassname}Service.getList${var.propertiesUp}(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("list${var.propertiesUp}", list${var.propertiesUp});
    }
    </#if>
</#list>

    private void setMsg(${simpleClassName} ${simpleClassname},HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", ${simpleClassname});
    }
}
